﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using University.Workshop.Model;
using System.Threading;
using System.IO;
using University.Workshop.DataAccess;
using University.Workshop.Business;
using System.Net;
using System.Collections.ObjectModel;
using University.Workshop.Model.CardGame;
using University.Workshop.DataAccess.LanguagePack.ClientLanguagePack;
using System.Globalization;

namespace University.Workshop.ClientApp
{
    /// <summary>
    /// Interaction logic for PokerTable.xaml
    /// </summary>
    public partial class PokerTable : Window
    {
        TableProperties TablesRules;
        string LanguageSelected;

        private string MessageWelcome = "Welcome ";
        private string MessageWinner = "the winner is ";
        private string MessageChips = " chips: ";
        private string MessageCongratulations = "Congratulations ";
        private string MessageYouAreInLevel = " you are Level: ";
        private string MessageName = "Name: ";
        private string MessageHand = "Hand: ";
        private string MessageChipsWon = "Chips won: ";

        private string MessageErrorTheBetIsNotInTheRangeOfRules = "The bet is not in the range of rules (Max, Min) -> (";
        private string MessageErrorYouHadRetired = "You had retired because you have less chips than the minimum bet";    
        private string MessageErrorAllPlayersLeftTable = "All players left the table. This item was automatically closed...";

        private string MessageChatPlayerJoined = "< has joined the table";
        private string MessageChatPlayerLeft = "< left the table";



        Client client;

        string[] bets = new string[5];

        //int DeckOfUser = 0;
        long LastBet=0;
        Client chat;
        Client Cards;
        bool isClosed = false;
        bool isClose = false;
        Collection<string> partners = new Collection<string>();
        string[] userChips = new string[5];
        string[] userLevel = new string[5];
       // Image_Manager manager = new Image_Manager();
        object mutex=new object();
        int number = 0;
        Thread chatThread;
        Thread wait;
        int port;
        long myActualBet = 0;
        long actualBet = 0;
        bool host = false;
        User Gamer = new User();
        string username;
        public int MyID { get; set; }
        RelationshipsManager relations=new RelationshipsManager();
        PokerServer server = new PokerServer();
        short time;
        Thread makePause;
        Thread threadTime;
        ProgressBar actual;
        bool pause;
        bool isMyTurn;
        int timePause = 30;
        Collection<long> timeWon = new Collection<long>();
        private Collection<Card> ListMyCard = new Collection<Card>();
        private Collection<Card> ListTableCard = new Collection<Card>();
        private Collection<LevelDatabase> levels = new Collection<LevelDatabase>();
        private LevelsManager levelsManager;
        Collection<long> ActualBets = new Collection<long>();
        public PokerTable()
        {
            InitializeComponent();
            levelsManager = new LevelsManager();
            time = 60;
            initializeProgressTime(ProgressTime1);
            initializeProgressTime(ProgressTime2);
            initializeProgressTime(ProgressTime3);
            initializeProgressTime(ProgressTime4);
            initializeProgressTime(ProgressTime5);
            threadTime = new Thread(startTime);
            makePause = new Thread(pauseAction);
            pause = false;
            isMyTurn = false;
            //DeckOfUser = 0; //11111111111111
        }
         ~PokerTable()
        {
         //   number = 10;
        }
        public void initializeProgressTime(ProgressBar progress)
        {
            time = 60;
            progress.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
            {
                progress.Minimum = 0;
                progress.Maximum = time;
                progress.Value = time;
                changeColor(Brushes.Blue, progress);
            }));
            
            labelTime.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate() { labelTime.Content= Convert.ToString(time); }));
            
        }

        private void ApplyLanguage()
        {
            this.MessageWelcome = ClientLanguagePack.PokerTableMessageWelcome;
            this.MessageWinner = ClientLanguagePack.PokerTableMessageWinner;
            this.MessageChips = ClientLanguagePack.PokerTableMessageChips;
            this.MessageCongratulations = ClientLanguagePack.PokerTableMessageCongratulations;
            this.MessageYouAreInLevel = ClientLanguagePack.PokerTableMessageYouAreInLevel;
            this.MessageName = ClientLanguagePack.PokerTableMessageName;
            this.MessageHand = ClientLanguagePack.PokerTableMessageHand;
            this.MessageChipsWon = ClientLanguagePack.PokerTableMessageChipsWon;

            this.MessageErrorTheBetIsNotInTheRangeOfRules = ClientLanguagePack.PokerTableMessageErrorTheBetIsNotInTheRangeOfRules;
            this.MessageErrorYouHadRetired = ClientLanguagePack.PokerTableMessageErrorYouHadRetired;
            this.MessageErrorAllPlayersLeftTable = ClientLanguagePack.PokerTableMessageErrorAllPlayersLeftTable;

            this.MessageChatPlayerJoined = ClientLanguagePack.PokerTableMessageChatPlayerJoined;
            this.MessageChatPlayerLeft = ClientLanguagePack.PokerTableMessageChatPlayerLeft;

            this.RetireButton.Content = ClientLanguagePack.PokerTableButtonRetire;
            this.Pass.Content = ClientLanguagePack.PokerTableButtonPass;
            this.Start.Content = ClientLanguagePack.PokerTableButtonStart;
            this.button1.Content = ClientLanguagePack.PokerTableButtonSendChat;
            this.button2.Content = ClientLanguagePack.PokerTableButtonBet;

            this.labelWinnerName.Content = ClientLanguagePack.PokerTableLabelWinnerName;
            this.labelWinnerHand.Content = ClientLanguagePack.PokerTableLabelWinnerHand;
            this.labelWinnerChips.Content = ClientLanguagePack.PokerTableLabelWinnerChips;
            this.label_StatisticTitle.Content = ClientLanguagePack.PokerTableLabelChanceToWin;
            this.label14.Content = ClientLanguagePack.PokerTableLabelYourCards;
            this.label13.Content = ClientLanguagePack.PokerTableLabelStatus;
            this.label11.Content = ClientLanguagePack.PokerTableLabelTimeYouHave;
        }

        public bool JoinTable(int port, string name,string IP,long chips, RelationshipsManager relations,int level,long timeHandWon)
         {
             
             isMyTurn = false;
             for (int i = 0; i < 5; i++)
             {
                 partners.Add("");
                 timeWon.Add(0);
                 ActualBets.Add(0);
             }
                 this.port = port;
             string user = "";
             this.relations = relations;
             client = new Client(port,IP);
             client.Send("00");
             string              temporaly = client.Receive();
             //   client.receive();
             // client.Send("consult");
             // client.receive();
             string[] users;
             number = client.SendData(name,chips,level,timeHandWon,TablesRules.TotalPlayers);
             if (number > 0)
             {

                 for (int ID = 0; ID < number; ID++)
                 {

                     
                     user = "";
                     //MemoryStream memory = client.reciveUserMemory(ref user);
                     //setImageTest(user, memory, ID, existImage);
                     user = client.ReceiveUser();
                     users = user.Split(' ');
                     partners[ID] = users[0];
                     userChips[ID] = users[1];
                     userLevel[ID] = users[2];
                     timeWon[ID] = Convert.ToInt32(users[3]);
                     bets[ID] = userChips[ID];
                     setImage(users[0],users[1], ID,users[2]);

                 } 
                 username = user;
                 MyID = number - 1;
             }
             else
                 return false;
             Cards = new Client(port, IP);
             Cards.Send("01");
             temporaly = Cards.Receive();

             wait = new Thread(new ThreadStart(receiveUser));
             wait.Start();
             // client.receive();
             //chat.receive();
             //chat.Send("regular");
             //chat.receive();
             chat = new Client(port,IP);
             chat.Send("02");
             chat.Receive();
             chat.Send("06 " + user + this.MessageChatPlayerJoined);
             return true;
         }
         
        public PokerTable(int port, User user, RelationshipsManager relations,Collection<LevelDatabase> levelsReceived)
        {
             
            InitializeComponent();

            levelsManager = new LevelsManager();
             time = 60;
            initializeProgressTime(ProgressTime1);
            initializeProgressTime(ProgressTime2);
            initializeProgressTime(ProgressTime3);
            initializeProgressTime(ProgressTime4);
            initializeProgressTime(ProgressTime5);
            threadTime = new Thread(startTime);
            makePause = new Thread(pauseAction);
            pause = false;
          //  Thread.Sleep(200);
            host = true;
            server.InitializeServer(2999);
            Thread.Sleep(400);
         if (!JoinTable(port, user.Name,"127.0.0.1",user.Chips, relations,user.UserLevel,user.TimeWon))
                throw new Exception();
            else
            {

                Start.Visibility = Visibility.Visible;
                Gamer = user;
                BetSlider.Minimum = 0;
                BetSlider.Maximum = user.Chips;
                MessageBox.Show(this.MessageWelcome + user.Name);
            }

         button2.IsEnabled = false;
         buttonPause.IsEnabled = false;

         //DeckOfUser = 1;//11111111111111111111
         
         levelsManager.SetLevels(levelsReceived);
        }

        public PokerTable(int port, User user, RelationshipsManager relations, Collection<LevelDatabase> levelsReceived, TableProperties tablesRules)
         {
             InitializeComponent();

             this.TablesRules = tablesRules;

             levelsManager = new LevelsManager();
             time = 60;
             initializeProgressTime(ProgressTime1);
             initializeProgressTime(ProgressTime2);
             initializeProgressTime(ProgressTime3);
             initializeProgressTime(ProgressTime4);
             initializeProgressTime(ProgressTime5);
             threadTime = new Thread(startTime);
             makePause = new Thread(pauseAction);
             pause = false;
             //  Thread.Sleep(200);
             host = true;
             server.InitializeServer(2999);
             Thread.Sleep(400);
             if (!JoinTable(port, user.Name, "127.0.0.1", user.Chips, relations, user.UserLevel, user.TimeWon))
                 throw new Exception();
             else
             {

                 Start.Visibility = Visibility.Visible;
                 Gamer = user;
                 BetSlider.Minimum = 0;
                 BetSlider.Maximum = user.Chips;
                 MessageBox.Show(this.MessageWelcome + user.Name);
             }

             button2.IsEnabled = false;
             buttonPause.IsEnabled = false;


             levelsManager.SetLevels(levelsReceived);
         }

        public PokerTable(int port, User user, RelationshipsManager relations, Collection<LevelDatabase> levelsReceived, TableProperties tablesRules, string languageSelected)
        {
            InitializeComponent();

            this.LanguageSelected = languageSelected;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();

            this.TablesRules = tablesRules;

            levelsManager = new LevelsManager();
            time = 60;
            initializeProgressTime(ProgressTime1);
            initializeProgressTime(ProgressTime2);
            initializeProgressTime(ProgressTime3);
            initializeProgressTime(ProgressTime4);
            initializeProgressTime(ProgressTime5);
            threadTime = new Thread(startTime);
            makePause = new Thread(pauseAction);
            pause = false;
            //  Thread.Sleep(200);
            host = true;
            server.InitializeServer(2999);
            Thread.Sleep(400);
            if (!JoinTable(port, user.Name, "127.0.0.1", user.Chips, relations, user.UserLevel, user.TimeWon))
                throw new Exception();
            else
            {

                Start.Visibility = Visibility.Visible;
                Gamer = user;
                BetSlider.Minimum = 0;
                BetSlider.Maximum = user.Chips;
                MessageBox.Show(this.MessageWelcome + user.Name);
            }

            button2.IsEnabled = false;
            buttonPause.IsEnabled = false;
            levelsManager.SetLevels(levelsReceived);            
        }

        public PokerTable(int port, User user,string IP ,RelationshipsManager relations,Collection<LevelDatabase> levelsReceived)
         {

             InitializeComponent();
             levelsManager = new LevelsManager();
             time = 60;
             initializeProgressTime(ProgressTime1);
             initializeProgressTime(ProgressTime2);
             initializeProgressTime(ProgressTime3);
             initializeProgressTime(ProgressTime4);
             initializeProgressTime(ProgressTime5);
             threadTime = new Thread(startTime);
             makePause = new Thread(pauseAction);
             pause = false;
             if (!JoinTable(port, user.Name,IP, user.Chips, relations,user.UserLevel,user.TimeWon))
                 throw new Exception();
             else
             {
                 Gamer = user;
                 BetSlider.Minimum = 0;
                 BetSlider.Maximum = user.Chips;
                 MessageBox.Show(this.MessageWelcome + user.Name);
             }

             button2.IsEnabled = false;
             buttonPause.IsEnabled = false;
             chatThread = null;
             levelsManager.SetLevels(levelsReceived);
         }

        public PokerTable(int port, User user, string IP, RelationshipsManager relations, Collection<LevelDatabase> levelsReceived, TableProperties tablesRules)
        {
            InitializeComponent();
            this.TablesRules = tablesRules;

            levelsManager = new LevelsManager();
            time = 60;
            initializeProgressTime(ProgressTime1);
            initializeProgressTime(ProgressTime2);
            initializeProgressTime(ProgressTime3);
            initializeProgressTime(ProgressTime4);
            initializeProgressTime(ProgressTime5);
            threadTime = new Thread(startTime);
            makePause = new Thread(pauseAction);
            pause = false;
            if (!JoinTable(port, user.Name, IP, user.Chips, relations, user.UserLevel, user.TimeWon))
                throw new Exception();
            else
            {
                Gamer = user;
                BetSlider.Minimum = 0;
                BetSlider.Maximum = user.Chips;
                MessageBox.Show(this.MessageWelcome + user.Name);
            }

            button2.IsEnabled = false;
            buttonPause.IsEnabled = false;
            chatThread = null;
            levelsManager.SetLevels(levelsReceived);
        }

        public PokerTable(int port, User user, string IP, RelationshipsManager relations, Collection<LevelDatabase> levelsReceived, TableProperties tablesRules, string languageSelected)
        {
            InitializeComponent();

            this.LanguageSelected = languageSelected;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();

            this.TablesRules = tablesRules;

            levelsManager = new LevelsManager();
            time = 60;
            initializeProgressTime(ProgressTime1);
            initializeProgressTime(ProgressTime2);
            initializeProgressTime(ProgressTime3);
            initializeProgressTime(ProgressTime4);
            initializeProgressTime(ProgressTime5);
            threadTime = new Thread(startTime);
            makePause = new Thread(pauseAction);
            pause = false;
            if (!JoinTable(port, user.Name, IP, user.Chips, relations, user.UserLevel, user.TimeWon))
                throw new Exception();
            else
            {
                Gamer = user;
                BetSlider.Minimum = 0;
                BetSlider.Maximum = user.Chips;
                MessageBox.Show(this.MessageWelcome + user.Name);
            }

            button2.IsEnabled = false;
            buttonPause.IsEnabled = false;
            chatThread = null;
            levelsManager.SetLevels(levelsReceived);            
        }

        public void ReceiveCard()
        {
            string[] message;
                try
                {
                       
                    while (true)
                    {
                            message = Cards.Receive().Split(' ');
                                
                        
                        if (message[0] == "01") //01 (numero de la carta que toca) (numero de la carta) (palo)
                                {
                                    ListTableCard.Add(Statistics.ToCard(message[3], message[2]));

                                    labelStatistic.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                    new Action(delegate()
                                    {
                                        string Result = Statistics.GetStatistics(ListMyCard, ListTableCard).ToString();
                                        this.labelStatistic.Content = Result;
                                    }));



                                    message[3] += message[2];
                                    // string strUri2 = String.Format(@"/University.Workshop.ClientApp;component/Images/Cards/{0}", message[2] + ".png");
                                    TurnDownImage(GiveMeImageCard(Convert.ToInt32(message[1])), message[3]);
                                    myActualBet = 0;
                                }
                                else if (message[0] == "02")
                                {
                                    ListMyCard.Add(Statistics.ToCard(message[3], message[2]));
                                    ListMyCard.Add(Statistics.ToCard(message[5], message[4]));

                                    message[3] += message[2];
                                    int actualCard = Convert.ToInt32(message[1]);
                                    // string strUri2 = String.Format(@"/University.Workshop.ClientApp;component/Images/Cards/{0}", message[2] + ".png");
                                    TurnDownImage(GiveMeImageCard(actualCard), message[3]);
                                    actualCard++;
                                    message[5] += message[4];
                                    TurnDownImage(GiveMeImageCard(actualCard), message[5]);
                                    myActualBet = 0;
                                    if (Convert.ToInt64(userChips[MyID]) < Convert.ToInt64(this.TablesRules.MinimumBet))
                                    {
                                            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                        {
                                            this.Close();
                                            MessageBox.Show("You had retired because you have less chips than the minimum bet", ":(");

                                        }));
                                        MessageBox.Show(this.MessageErrorYouHadRetired, ":(");

                                    }
                                }
                                else if (message[0] == "03")
                                {
                                    ListMyCard.Clear();
                                    ListTableCard.Clear();
                                    int LastLevel = Convert.ToInt32(userLevel[Convert.ToInt32(message[1])]);
                                    if (MyID == Convert.ToInt32(message[1]))
                                    {
                                        Gamer.Chips += Convert.ToInt64(message[2]);
                                        Gamer.TimeWon++;
                                        
                                        levelsManager.LevelUp(Gamer);
                                    }
                                    timeWon[Convert.ToInt32(message[1])]++;
                                    userChips[Convert.ToInt32(message[1])] = (Convert.ToInt64(userChips[Convert.ToInt32(message[1])]) + Convert.ToInt64(message[2])).ToString();
                                    DecreaseChips(getLabel(Convert.ToInt32(message[1])), (-1) * Convert.ToInt64(message[2]));
                                    labelMessage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                 new Action(delegate() { labelMessage.Content = this.MessageWinner + partners[Convert.ToInt32(message[1])] + this.MessageChips + message[2]; }));
                                    
                                    for (int i = 0; i < 7; i++)
                                    {
                                        myActualBet = 0;
                                        TurnDownImage(GiveMeImageCard(i), "CardBack_Blue");
                                    }
                                    User userGamer = new User();
                                    userGamer.TimeWon = timeWon[Convert.ToInt32(message[1])];
                                    userGamer.UserLevel = Convert.ToInt32(userLevel[Convert.ToInt32(message[1])]);
                                    userGamer.Chips = Convert.ToInt64(userChips[Convert.ToInt32(message[1])]);
                                    if (levelsManager.LevelUp(userGamer))
                                    {

                                        userLevel[Convert.ToInt32(message[1])] = Convert.ToString(userGamer.UserLevel);
                                        labelInfoLevel.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                        {                                           
                                            labelInfoLevel.Content = this.MessageCongratulations + partners[Convert.ToInt32(message[1])] + this.MessageYouAreInLevel + userLevel[Convert.ToInt32(message[1])];
                                            
                                        }));
                                        changePicture(GiveMeImageLevel(Convert.ToInt32(message[1])), "LevelImages/Level" + userLevel[Convert.ToInt32(message[1])] + ".jpg");
                                        Label label = GiveMeLabelLevel(Convert.ToInt32(message[1]));
                                        string path = userLevel[Convert.ToInt32(message[1])] + Gamer.GetLevelFromOther(Convert.ToInt32(userLevel[Convert.ToInt32(message[1])]));
                                        changeLabelLevel(label, path);
                                    }
                                    labelWinnerName.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                        {
                                            labelWinnerName.Content = "Name: " + partners[Convert.ToInt16(message[1])];
                                            labelWinnerHand.Content = "Hand: " + message[3];
                                            labelWinnerChips.Content = "Chips won: " + message[2];
                                        }));
                                    Thread.Sleep(1000);
                                }
                            Cards.Send("again");
                        }
                    

                }
                catch (Exception)
                {
                    /*this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                     new Action(delegate()
                     {
                         this.Close();
                     }));
                    MessageBox.Show("Try again, an error ocurred...");*/
                    
                }
            
               
            
        }
        /*
        private string WinnerHandValue(string value)
        {
            switch (value)
            {
                case "15":
                    return "One Pair";
                case "16":
                    return "Two Pair";
                case "17":
                    return "Three Of The King";
                case "18":
                    return "Straight";
                case "19":
                    return "Flush";
                case "20":
                    return "Full House";
                case "21":
                    return "Poker";
                case "22":
                    return "Straight Flush";
                case "23":
                    return "Royal Flush";
                case "only":
                    return "Default";
                
            }
            return "High Card";   
        }
        */
        private void TurnDownImage(Image image,string path)
        {
            image.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                     new Action(delegate()
                     {
                         Uri uri;
                         if (Gamer.DeckUserPresent == 3)
                             uri = new Uri("Images/ImagesDecks/Deck3/" + path + ".jpg", UriKind.Relative);
                         else if( Gamer.DeckUserPresent == 2)
                                uri = new Uri("Images/ImagesDecks/Deck2/" + path + ".png", UriKind.Relative);
                              else if (Gamer.DeckUserPresent == 1)
                                 uri = new Uri("Images/ImagesDecks/Deck1/" + path + ".png", UriKind.Relative);
                                   else
                                      uri = new Uri("Images/Cards/" + path + ".png", UriKind.Relative);
                         ImageSource imgSource = new BitmapImage(uri);
                         image.Source = imgSource;
                     }));
        }
        private Image GiveMeImageCard(int index)
        {
            switch (index)
            { 
                case 0:
                    return imageCard1;
                case 1:
                    return imageCard2;
                case 2:
                    return imageCardTable1;
                case 3:
                    return imageCardTable2;

                case 4:
                    return imageCardTable3;

                case 5:
                    return imageCardTable4;

                case 6:
                    return imageCardTable5;

            }
            return null;
        }
        private Image GiveMeImageLevel(int index)
        { 
            switch(index)
            {
                case 0:
                    return imageLevel1;
                case 1:
                    return imageLevel2;
                case 2:
                    return imageLevel3;
                case 3:
                    return imageLevel4;
                case 4:
                    return imageLevel5;
            }
            return null;
        }
        private Label GiveMeLabelLevel(int index)
        {
            switch (index)
            {
                case 0:
                    return labelLevel1;
                case 1:
                    return labelLevel2;
                case 2:
                    return labelLevel3;
                case 3:
                    return labelLevel4;
                case 4:
                    return labelLevel5;
            }
            return null;
        }
        void Move(int chair)
        {
            if (chair < MyID)
            { MyID--; }
            for (int moving = chair; moving < number; moving++)
            {
                
                setImage(partners[moving+1],userChips[moving+1],moving,userLevel[moving+1]);
                partners[moving] = partners[moving + 1];
                userChips[moving] = userChips[moving + 1];
                userLevel[moving] = userLevel[moving + 1];
                timeWon[moving] = timeWon[moving + 1];
            }
            setImage(" "," ",number," ");
            partners[number] = " ";
            userLevel[number] = " ";
        }
        private void pauseAction(Object progressReceived)
        {
            if (number == 1 && host)
            {
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                          new Action(delegate()
                          {
                              this.Close();
                          }));

                MessageBox.Show(this.MessageErrorAllPlayersLeftTable);
            }
            else
            {
                ProgressBar progress = (ProgressBar)progressReceived;
                pause = true;
                timePause = 30;
                while (timePause > 0)
                {
                    if (number == 1 && host)
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                  new Action(delegate()
                                  {
                                      this.Close();
                                  }));

                        MessageBox.Show(this.MessageErrorAllPlayersLeftTable);
                    }
                    timePause--;
                    progress.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                         new Action(delegate()
                         { labelPause.Content = timePause.ToString(); }));

                    Thread.Sleep(1000);
                }
                pause = false;
                timePause = 30;
            }
            
        }
        public void receiveUser()
        {
            while (number <= 5 )
            {
                try
                {
                    string[] data = client.Receive().Split(' ');
                    if (data[0] == "01")
                    {
                        client.Send("received");
                        setImage(data[1],data[2],number,data[3]);
                        partners[number] = data[1];
                        userChips[number] = data[2];
                        userLevel[number] = data[3];
                        timeWon[number] = Convert.ToInt64(data[4]);
                        bets[number] = userChips[number];
                        number++;
                    }
                    else
                    {
                        if (data[0] == "02")
                        {
                            number--;
                            Cuadro.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate() { Cuadro.Items.Add(data[1] + this.MessageChatPlayerLeft); }));
                            Move(Convert.ToInt32(data[2]));
                        }
                        else
                        {
                            if (data[0] == "03")
                            {
                                string word = string.Empty;
                                for (int concat = 1; concat < data.Length; concat++)
                                {
                                    word = word + data[concat] + " ";
                                }
                                Cuadro.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                new Action(delegate() { Cuadro.Items.Add(word); }));

                            }
                            else
                            {
                                if (data[0] == "04")
                                {
                                    Start.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                    new Action(delegate() { Start.Visibility = Visibility.Visible; }));

                                    client.Send("Activate");
                                }
                                else
                                {
                                    if (data[0] == "05") //pass
                                    {

                                        isMyTurn = true;
                                        BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                  new Action(delegate() { BetSlider.IsEnabled = true; }));
                                        button2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { button2.IsEnabled = true; }));
                                        RetireButton.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                     new Action(delegate() { RetireButton.IsEnabled = true; }));
                                        Pass.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { Pass.IsEnabled = true; }));
                                        button2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { button2.IsEnabled = true; }));
                                        buttonPause.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonPause.IsEnabled = true; }));
                                        BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                  new Action(delegate() { BetSlider.Maximum = Convert.ToInt64(data[1]); }));
                                        buttonPlus.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonPlus.IsEnabled = true; }));
                                        buttonMinus.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonMinus.IsEnabled = true; }));
                                        
                                        client.Send("Enabled");
                                    }
                                    else if (data[0] == "06") //aumentar bet
                                    {

                                        long minimum = Convert.ToInt64(userChips[0]);

                                        for (int i = 1; i < number; i++)
                                        {
                                            long value = Convert.ToInt64(userChips[i]);
                                            if (value < minimum)
                                                minimum = value;

                                        }
                                        isMyTurn = true;
                                       
                                        //if (myActualBet > Convert.ToInt64(data[1])) myActualBet = 0;
                                        long betValue=Convert.ToInt64(data[1]);
                                        RetireButton.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                  new Action(delegate() { RetireButton.IsEnabled = true; }));
                                        BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                      new Action(delegate() { BetSlider.IsEnabled = true; }));
                                        button2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { button2.IsEnabled = true; }));
                                        buttonPause.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonPause.IsEnabled = true; }));
                                        Pass.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { Pass.IsEnabled = true; Pass.Content = ("go(" + betValue + ")"); }));
                                        buttonPlus.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonPlus.IsEnabled = true; }));
                                        buttonMinus.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { buttonMinus.IsEnabled = true; }));
                                        
                                       
                                            
                                        
                                        if ( minimum==betValue)
                                        {
                                            button2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                            new Action(delegate() { button2.IsEnabled = false; }));
                                            
             
                                        }
                                        else
                                        {

                                         



                                            BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
     new Action(delegate() { BetSlider.Minimum = betValue + 1; }));

                                          
                                              BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                      new Action(delegate()
                                      {
                                              BetSlider.Maximum = minimum;
                                          }));
                                            BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                          new Action(delegate() { BetSlider.Value = BetSlider.Minimum; }));
                                         
                                           
                                        }

                                        actualBet = betValue;
                                        client.Send("Bet");
                                    }
                                    else if (data[0] == "07")
                                    {
                                        //MessageBox.Show("server disconected");
                                        //Destroyer();
                                        isClosed = true;
                                        if (host) {
                                           Thread Test=new Thread(server.DisconnectServer);
                                           Test.Start();
                                           Test.Join();
                                            number = 6;
                                        }
                                        else
                                        {
                                            isMyTurn = false;
                                            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                            new Action(delegate() { this.Close(); }));
                                        }
                                    }
                                    else if (data[0] == "08") // primera vez
                                    {

                                        chatThread = new Thread(ReceiveCard);
                                        chatThread.Start();
                                        labelPause.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                            new Action(delegate() { labelPause.Content = "30"; timePause = 30; pause = false; }));
                                        actual = ProgressTime1;
                                        threadTime = new Thread(startTime);
                                        threadTime.Start(ProgressTime1);
                                    }
                                    else if (data[0] == "09") // aviso a todos que se paso y/o aposto
                                    {
                                        if (threadTime.IsAlive)
                                        {
                                            threadTime.IsBackground = true;
                                            threadTime.Abort();
                                            
                                        }
                                        if (makePause.IsAlive)
                                        {
                                            makePause.IsBackground = true;
                                            makePause.Abort();
                                        }
                                        labelPause.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                            new Action(delegate() { labelPause.Content = "30"; timePause = 30; pause = false; }));
                                        initializeProgressTime(actual);
                                        actual = getProgress(partners.IndexOf(data[1]));
                                        threadTime = new Thread(startTime);
                                        threadTime.Start(actual);
                                        labelMessage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
             new Action(delegate() { labelMessage.Content = data[2] +"->"+ data[3]; }));

                                        long newChips;
                                        try
                                        {

                                            newChips = Convert.ToInt64(data[3]);
                                            int index = partners.IndexOf(data[2]);
                                            ActualBets[index] = newChips;
                                        }
                                        catch(FormatException)
                                        {
                                        
                                        }
                                        client.Send("Ok");
                                    }
                                    else if (data[0] == "10")
                                    {
                                        makePause = new Thread(pauseAction);
                                        makePause.Start(actual);
                                    }
                                    else if (data[0] == "11")//se paso de ronda completa
                                    {
                                        LastBet = 0;
                                        
                                        if (threadTime.IsAlive)
                                        {
                                            threadTime.IsBackground = true;
                                            threadTime.Abort();

                                        }
                                        if (makePause.IsAlive)
                                        {
                                            makePause.IsBackground = true;
                                            makePause.Abort();
                                        }
                                        
                                        labelPause.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                            new Action(delegate() { labelPause.Content = "30"; timePause = 30; pause = false; }));
                                        initializeProgressTime(actual);
                                        actual = getProgress(partners.IndexOf(data[2]));
                                        threadTime = new Thread(startTime);
                                        threadTime.Start(actual);
                                        labelMessage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate() { labelMessage.Content = "Se paso a la ronda: " + data[1]; }));
                                        BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
      new Action(delegate() { BetSlider.Minimum = 0; }));
                                        long newChips;
                                        try
                                        {
                                            newChips = Convert.ToInt64(data[4]);
                                            int index = partners.IndexOf(data[3]);
                                            ActualBets[index] = newChips;
                                              for (int i = 0; i < number; i++)
                                              {
                                                  userChips[i] = (Convert.ToInt64(userChips[i])-ActualBets[i]).ToString();
                                                  DecreaseChips(getLabel(i), ActualBets[i]);
                                                  ActualBets[i] = 0;
                                                  
                                              }
          
         
                                        
                                            
             
                                            
                                        }
                                        catch (FormatException)
                                        {
                                            for (int i = 0; i < number; i++)
                                            {
                                                userChips[i] = (Convert.ToInt64(userChips[i]) - ActualBets[i]).ToString();
                                                DecreaseChips(getLabel(i), ActualBets[i]);
                                                ActualBets[i] = 0;

                                            }
                                        }
                                        Gamer.Chips = Convert.ToInt64(userChips[MyID]);
                                        client.Send("Ok");
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    if (host)
                    {
                     Thread Test=new Thread(server.DisconnectServer);
                     Test.Start();
                     Test.Join();
                    }//MessageBox.Show(ex.ToString());
                }
            }
            //MessageBox.Show("Bye");
        }
        public void SetChips(Label newLabel, int index)
        {

       newLabel.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(delegate() {userChips[index] = newLabel.Content.ToString(); }));
         
        }
        public void DecreaseChips(Label newLabel,long amount)
        {
            newLabel.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
    new Action(delegate() { newLabel.Content = (Convert.ToInt32(newLabel.Content) - amount).ToString(); }));
            
        }
        public Label getLabel(int index)
        {
            switch (index)
            {
                case 0:
                    return label6;
                case 1:
                    return label7;
                case 2:
                    return label8;
                case 3:
                    return label9;
                case 4:
                    return label10;
            }
            return null;
        }
        public ProgressBar getProgress(int index)
        {
            switch (index)
            { 
                case 0:
                    return ProgressTime1;
                case 1:
                    return ProgressTime2;
                case 2:
                    return ProgressTime3;
                case 3:
                    return ProgressTime4;
                case 4:
                    return ProgressTime5;
            }
            return null;
        }
        public void changeColor(SolidColorBrush color, ProgressBar bar)
        {
            bar.ApplyTemplate();
            ((Panel)bar.Template.FindName("Animation", bar)).Background = color;


        }
        public void startTime(Object timeBarReceived)
        {
            if (number == 1 && host)
            {
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                          new Action(delegate()
                          {
                              this.Close();
                          }));

                MessageBox.Show(this.MessageErrorAllPlayersLeftTable);
            }
            else
            {
                ProgressBar timeBar = (ProgressBar)timeBarReceived;
                while (time >= 0)
                {
                    if (!pause)
                    {
                        if (number == 1 && host)
                        {
                            
                            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                      new Action(delegate()
                                      {
                                          this.Close();
                                      }));
                            MessageBox.Show(this.MessageErrorAllPlayersLeftTable);
                        }
                        timeBar.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                         new Action(delegate()
                         {

                             timeBar.Value--;
                             labelTime.Content = time;
                             if (time <= 30 && time > 15)
                                 changeColor(Brushes.Yellow, timeBar);
                             if (time > 0 && time <= 15)
                                 changeColor(Brushes.Red, timeBar);

                         }));
                        Thread.Sleep(1000);
                        time--;
                    }
                }
                if (isMyTurn)
                {
                    labelMessage.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate()
                    { labelMessage.Content = " "; }));
                    BetSlider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            { BetSlider.IsEnabled = false; }));

                    button2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            { button2.IsEnabled = false; }));

                    Pass.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            { Pass.IsEnabled = false; }));

                    RetireButton.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            {
                RetireButton.IsEnabled = false;
            }));
                    chat.Send("34 " + Gamer.Name + " " + actualBet);
                }

                initializeProgressTime(timeBar);
            }
            
        }
        /*private void pauseAction(Object timeBarReceived)
        {
            ProgressBar timeBar = (ProgressBar)timeBarReceived;
            pause = true;
            int timePause = 30;
            while (timePause > 0)
            {
                timePause--;
                timeBar.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                     new Action(delegate()
                     { labelPause.Content = timePause.ToString(); }));

                Thread.Sleep(1000);
            }
            pause = false;
        }
        */
        // Clock part
        private void changeLabelLevel(Label label, string message)
        {
            label.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate() { label.Content = message; }));
        }
        private void changePicture(Image image, string path)
        {
            image.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate()
            {
                Uri uri = new Uri(path, UriKind.Relative);

                ImageSource imgSource = new BitmapImage(uri);

                image.Source = imgSource;
            }));
           
        }
        public void setImage(string name,string chips,int ID,string Level)
        {
            User user= new User();
            if(Level!=" ")
            user.UserLevel=Convert.ToInt32(Level);
           // manager = new Image_Manager();
            switch (ID)
            { 
                case 0:
                    
                        label1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate() { label1.Content=name; }));
                        imageLevel1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate() { 
                                string path="LevelImages/Level"+Level+".jpg";
                                if(Level!=" ")
                                    changePicture(imageLevel1,path);
                                else
                                    imageLevel1.Visibility = Visibility.Hidden;
                        }));
                                
                        setChips(0,chips);
                        labelLevel1.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate()
                                        {
                                            if (Level != " ") labelLevel1.Content = Level + " " + user.GetLevel;
                                            else labelLevel1.Content = Level;
                                        }));
                break;
                case 1:
                        label2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate() { label2.Content=name; }));
                        imageLevel2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate()
                        {
                            string path = "LevelImages/Level" + Level + ".jpg";
                            if(Level!=" ")
                                changePicture(imageLevel2, path);
                            else
                                imageLevel2.Visibility = Visibility.Hidden;
                        }));
                        setChips(1, chips);
                        labelLevel2.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                    new Action(delegate() {if(Level!=" ") labelLevel2.Content = Level + " " + user.GetLevel; 
                                                            else labelLevel2.Content = Level;}));
                        break;
                case 2:
                            label3.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate() { label3.Content=name; }));
                            imageLevel3.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate()
                                {
                                    string path = "LevelImages/Level" + Level + ".jpg";
                                    if(Level!=" ")
                                        changePicture(imageLevel3, path);
                                    else
                                        imageLevel3.Visibility = Visibility.Hidden;
                                }));
                            setChips(2, chips);
                            labelLevel3.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { if(Level!=" ") labelLevel3.Content = Level + " " + user.GetLevel;
                                        else labelLevel3.Content = Level;
                                        }));
                break;
                case 3:
                            label4.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate() { label4.Content=name; }));
                            imageLevel4.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate()
                            {
                                string path = "LevelImages/Level" + Level + ".jpg";
                                if(Level!=" ")
                                    changePicture(imageLevel4, path);
                                else
                                    imageLevel4.Visibility = Visibility.Hidden;
                            }));
                            setChips(3, chips);
                            labelLevel4.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() { if(Level!=" ")labelLevel4.Content = Level + " " + user.GetLevel;
                                        else labelLevel4.Content = Level;
                                        }));
                break;
                case 4:
                            label5.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate() { label5.Content=name; }));
                            imageLevel5.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate()
                                {
                                    string path = "LevelImages/Level" + Level + ".jpg";
                                    if (Level != " ")
                                        changePicture(imageLevel5, path);
                                    else
                                        imageLevel5.Visibility = Visibility.Hidden;
                                }));
                            setChips(4, chips);
                            labelLevel5.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                                        new Action(delegate() {if(Level!=" ") labelLevel5.Content = Level + " " + user.GetLevel;
                                        else labelLevel5.Content = Level;
                                        }));
                break;
            }
        }

        private void setChips(int Index,string chips)
        {
            switch (Index)
            { 
                case 0:
                    label6.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { label6.Content = chips; }));
                    break;

                case 1:
                    label7.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { label7.Content = chips; }));
                    break;

                case 2:
                    label8.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { label8.Content = chips; }));
                    break;

                case 3:
                    label9.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { label9.Content = chips; }));
                    break;

                case 4:
                    label10.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { label10.Content = chips; }));
                    break;
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            chat.Send("06 " + username + "< " + Message.Text);
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
        }

        private void image6_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }
        public void Destroyer()
        {

            if (!host)
            {
                if (isMyTurn)
                {
                    chat.Send("35 " + actualBet + " " + Gamer.Name);

                }
                else
                {

                    if (!isClosed)
                        chat.Send("15 " + Gamer.Name);
                }
                
            }
            else
            {
                chat.Send("21");
                wait.Join();        
            }
            client.Dispose();
            Cards.Dispose();
            chat.Dispose();
            //chat.receive();
            if (chatThread != null)
            {
                if (chatThread.IsAlive)
                {
                    chatThread.IsBackground = true;
                    chatThread.Abort();

                }
            }
            if (wait.IsAlive)
            {
                wait.IsBackground = true;
                wait.Abort();
               
            }
            if (threadTime.IsAlive)
            {
                threadTime.IsBackground = true;
                threadTime.Abort();
            }
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Destroyer();
    
        }

        public User lookingFor(string userName)
        {
            foreach (User user in relations.All)
            {
                if (user.Name == userName)
                    return user;
            }
            return null;
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //quitar linea de comentario
            /*int index=0;
            if (Cuadro.SelectedIndex != -1 && Cuadro.SelectedValue != null)
            {
                string userSelected="", selected = Convert.ToString(Cuadro.SelectedItem);
                if (selected != null)
                {
                    if (selected[0] == ' ')
                        index = 1;
                    while (selected[index] != '<')
                    {
                        userSelected = userSelected + selected[index];
                        index++;
                    }
                    User userOnly = lookingFor(userSelected);
                    User actualUser = lookingFor(username);
                    Profile profile = new Profile(actualUser,userOnly,relations);
                    profile.ShowDialog();
                }
                Cuadro.SelectedIndex = -1;
                Cuadro.SelectedValue = null;
            }*/
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            button2.IsEnabled = true;
            buttonPause.IsEnabled = true;
            Start.Visibility = Visibility.Hidden;
            try
            {
                chat.Send("18 " + MyID);
            }
            catch (IOException)
            { }
        }

        private void Pass_Click(object sender, RoutedEventArgs e)
        {
            

            /*if (BetSlider.Value == BetSlider.Maximum)
            {
                if (allIn == 0)
                    allIn = (long)BetSlider.Value;
                chat.Send("71 " + allIn + " " + myActualBet+" "+Gamer.Name);
                myActualBet = actualBet - myActualBet;

            }
            else*/
           
                myActualBet = actualBet /*- myActualBet*/;
            chat.Send("19 " + actualBet + " " + myActualBet);
            chat.Receive();
          
            Gamer.Chips -= myActualBet;
            BetSlider.Maximum = Gamer.Chips;
            if (BetSlider.Minimum > BetSlider.Maximum)
                BetSlider.Minimum = BetSlider.Maximum;
            isMyTurn = false;
            labelMessage.Content = " ";
            myActualBet = 0;
            Pass.IsEnabled = false;
            BetSlider.IsEnabled = false;
            button2.IsEnabled = false;
            RetireButton.IsEnabled = false;
            buttonPause.IsEnabled = false;
            buttonPlus.IsEnabled = false;
            buttonMinus.IsEnabled = false;
            labelInfoLevel.Content = " ";
        }

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {
            myActualBet = Convert.ToInt64(textBox1.Text);

            long MinimunBet = Convert.ToInt64(this.TablesRules.MinimumBet);
            long MaximunBet = Convert.ToInt64(this.TablesRules.MaximumBet);
            if (myActualBet < MinimunBet || myActualBet > MaximunBet)
            {                
                MessageBox.Show(this.MessageErrorTheBetIsNotInTheRangeOfRules + MaximunBet + ", " + MinimunBet + ")", ":-O");
            }
            else
            {
                labelInfoLevel.Content = " ";


                /* if (BetSlider.Value == BetSlider.Maximum)
                 {
                     if (allIn == 0)
                         allIn = (long)BetSlider.Value;
                     chat.Send("71 " + allIn + " " + myActualBet + " " + Gamer.Name);

                 }
                 else*/
                chat.Send("20 " + BetSlider.Value + " " + BetSlider.Value);
                Gamer.Chips =Gamer.Chips- (Convert.ToInt64(BetSlider.Value) - LastBet);
                LastBet = Convert.ToInt64(BetSlider.Value);
                BetSlider.Maximum = Gamer.Chips;
                if (BetSlider.Minimum > BetSlider.Maximum)
                    BetSlider.Minimum = BetSlider.Maximum;
                RetireButton.IsEnabled = false;
                buttonPause.IsEnabled = false;
                labelMessage.Content = " ";
                isMyTurn = false;
                BetSlider.IsEnabled = false;
                button2.IsEnabled = false;
                Pass.IsEnabled = false;
                buttonPlus.IsEnabled = false;
                buttonMinus.IsEnabled = false;
           
            }
        }

        private void BetSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            textBox1.Text = BetSlider.Value.ToString();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (!isClose)
                Destroyer();
        }

        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            isClose = true; Destroyer();
        }

        private void ProgressTime1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

        }

        private void Retire_Click(object sender, RoutedEventArgs e)
        {
            labelInfoLevel.Content = " ";
            labelMessage.Content = " ";
            BetSlider.IsEnabled = false;
            button2.IsEnabled = false;
            Pass.IsEnabled = false;
            RetireButton.IsEnabled = false;
            buttonPause.IsEnabled = false;
            buttonPlus.IsEnabled = false;
            buttonMinus.IsEnabled = false;
           
            chat.Send("34 "+Gamer.Name+" "+actualBet);
        }

        private void buttonPause_Click(object sender, RoutedEventArgs e)
        {
            labelInfoLevel.Content = " ";
            buttonPause.IsEnabled = false;
            chat.Send("36 "+Gamer.Name);
        }

        public long allIn = 0;

        private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {string res="";
        for (int i = 0; i < number; i++)
            res += (userChips[i] + " ");
        MessageBox.Show(res);
        }

        private void buttonMinus_Click(object sender, RoutedEventArgs e)
        {
            if (BetSlider.Value > BetSlider.Minimum)
                BetSlider.Value--;
        }

        private void buttonPlus_Click(object sender, RoutedEventArgs e)
        {
            if (BetSlider.Value < BetSlider.Maximum)
                BetSlider.Value++;
        
        }
    }
}
